package tech.heptagram.staff.util;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;


/**
 * 拼音工具类
 *
 * @author Zi Lai Ye
 * @date 2017/8/7
 */
public class PinyinUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(PinyinUtils.class);

    public final static String SUBFIX_EMAIL = "@zhongfl.com";

    public final static String COMMA_STRING = ",";

    public static String convertToPinyinString(String str, String separator) throws PinyinException {

        if (StringUtils.isEmpty(str)) {
            return "";
        }

        String result = PinyinHelper.convertToPinyinString(str, separator, PinyinFormat.WITHOUT_TONE);

        return result;
    }

    /**
     * 生成员工姓名拼音
     *
     * @param name 员工姓名
     * @return
     * @throws PinyinException
     */
    public static String generateStaffNamePinyin(String name) throws PinyinException {
        return convertToPinyinString(name, "");
    }

    /**
     * 生成员工姓名拼音
     * @param name  员工姓名
     * @param number    追加的数字
     * @return
     * @throws PinyinException
     */
    public static String generateStaffNamePinyin(String name,int number) throws PinyinException {
        name = name + number;
        return convertToPinyinString(name, "");
    }

    /**
     * 生成员工email
     *
     * @param name 员工姓名
     * @return
     * @throws PinyinException
     */
    public static String generateStaffEmail(String name) throws PinyinException {
        return generateStaffEmail(name, null);
    }

        /**
         * 生成员工email
         * @param name 员工姓名
         * @param number   追加的数字
         * @return
         * @throws PinyinException
         */
    public static String generateStaffEmail(String name,Integer number) throws PinyinException {
        String names = convertToPinyinString(name, COMMA_STRING);

        if (StringUtils.isEmpty(names)) {
            return names;
        }

        String[] pinyins = StringUtils.split(names, COMMA_STRING);

        StringBuffer emailTemp = new StringBuffer();
        for (int i = 0; i < pinyins.length; i++) {
            emailTemp.append(pinyins[i]);
            if (i == 0 && i != pinyins.length - 1) {
                emailTemp.append(".");
            }
        }
        if(Objects.nonNull(number)){
            emailTemp.append(number);
        }
        emailTemp.append(SUBFIX_EMAIL);
        return emailTemp.toString();
    }

}
